package com.ytxg.health_management.controller;


import com.ytxg.health_management.pojo.dto.DictDto;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.util.MyException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/system")
public class SystemController {

    @Value("${images.url}")
    private String basePath;


    @PostMapping("/uploadImg")
    public Result<String> uploadImg(@RequestBody MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String fileName =dateDir +"/"+ UUID.randomUUID().toString() + suffix;

        File dir = new File(basePath+dateDir);
        if (!dir.exists()){
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + fileName));
            return Result.success(fileName);
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("上传失败");
        }

    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) {

        try {
            //输入
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+fileName));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new MyException("下载失败"+e);
        }

    }

}
